package org.opens.netty.chatServer.server.handle;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.opens.netty.chatServer.server.session.SessionFactory;

@Slf4j
@ChannelHandler.Sharable
public class QuitHandle extends ChannelInboundHandlerAdapter {

    /**
     * channel连接断开时会触发该方法
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 将断开的连接从会话管理器中移除掉
        SessionFactory.getSession().unbind(ctx.channel());
        log.info("{} 已断开", ctx.channel());
    }

    /**
     * 当捕捉到异常时触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 将断开的连接从会话管理器中移除掉
        SessionFactory.getSession().unbind(ctx.channel());
        log.info("{} 异常断开: {}", ctx.channel(), cause.getMessage());
    }
}
